import { Model } from 'dva';
import { getFilterList } from 'utils';
import { readList, changeTag } from '../services'

export interface ListItem {
  status: string;
  type: string;
  resources: string[];
  ip: string;
  os: string;
  name: string;
  id: number;
  location: string;
}
export type ListType = ListItem[]


const agent: Model = {
  namespace: 'agent',

  state: {
    shape: 'list',
    allList: [],
    idleList: [],
    buildingList: [],
    physicalList: [],
    virtualList: [],
  },

  effects: {
    *read(_, { call, put }) {
      const res = yield call(readList);
      let idleList: ListType= [], buildingList: ListType = [], physicalList: ListType = [], virtualList: ListType = [];

      if (res.length) {
         idleList = getFilterList(res, 'status', 'idle');
         buildingList = getFilterList(res, 'status', 'building');
         physicalList = getFilterList(res, 'type', 'physical');
         virtualList = getFilterList(res, 'type', 'virtual');
      }

      yield put({
        type: 'save',
        payload: {
          idleList,
          buildingList,
          physicalList,
          virtualList,
          allList: res,
        },
      });
    },

    *changeTag({ payload, callback, mark }, { call, put }) {
      const { instance, tag } = payload;
      const { id, resources } = instance;
      const arr = mark === 'create' ? [...resources, ...tag.split(',')] : resources.filter((e: string) => e !== tag);
      // if (mark === 'create') {
      //   arr = [...resources, ...tag.split(',')]
      // } else {
      //   arr = resources.filter((e: string) => e !== tag);
      // }
      const res = yield call(changeTag, id, { ...instance, resources: arr  });

      if (res.id) {
        yield put({
          type: 'read',
        })
      }

      if (callback) {
        callback();
      }
    }
  },

  reducers: {
    save (state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default agent;
